#include "FriendModel.hpp"
#include "mysqldb.hpp"

using namespace std;
// 添加好友关系
bool FriendModel::insert(int user_id, int friend_id){
    // 1.组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "insert into friend values(%d , %d);",user_id, friend_id);
    
    MySQL mysql;
    if(mysql.connect()){
        if(mysql.update(sql)){
            return true;
        }
    }
    return false;
}

//返回用户好友列表
vector<User> FriendModel::query(int user_id){
    //组装SQL语句
    char sql[1024] = {0};
    //inner连接，on是连接条件
    sprintf(sql, "select a.id, a.name, a.state from user a inner join friend b on b.friend_id = a.id where b.userid = %d;", user_id);

    vector<User> vec;
    MySQL mysql;
    if(mysql.connect()){
        MYSQL_RES *result = mysql.query(sql);//查询成功
        if(result != nullptr){
            MYSQL_ROW row;
            while((row = mysql_fetch_row(result)) != nullptr){ //有遍历结果集
                User user;
                user.set_id(atoi(row[0]));
                user.set_name(row[1]);
                user.set_state(row[2]);
                vec.push_back(user);
            }
            //释放资源，否则内存不断泄露
            mysql_free_result(result);
        }
    }
    return vec;
}

